<template>
  <div class="order-container">
    <a-card>
      <!-- 搜索表单 -->
      <div class="search-wrapper">
        <a-form layout="inline" :model="searchForm">
          <!-- 常用搜索字段 -->
          <div class="search-row">
            <a-form-item label="订单编号">
              <a-input v-model:value="searchForm.id" placeholder="请输入订单编号" />
            </a-form-item>
            <a-form-item label="用户名">
              <a-input v-model:value="searchForm.userName" placeholder="请输入用户名" />
            </a-form-item>
            <a-form-item label="商品名称">
              <a-input v-model:value="searchForm.productName" placeholder="请输入商品名称" />
            </a-form-item>
            <a-form-item label="订单状态">
              <a-select v-model:value="searchForm.orderStatus" placeholder="请选择" allowClear style="width: 120px">
                <a-select-option v-for="(value, key) in ORDER_STATUS" :key="key" :value="value">
                  {{ ORDER_STATUS_TEXT[value] }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="search-buttons">
              <a-space>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button @click="handleReset">重置</a-button>
                <a-button type="link" @click="showAdvanced = !showAdvanced">
                  {{ showAdvanced ? '收起' : '展开' }}
                  <template #icon>
                    <down-outlined :style="{ transform: showAdvanced ? 'rotate(180deg)' : '' }" />
                  </template>
                </a-button>
              </a-space>
            </a-form-item>
          </div>

          <!-- 高级搜索 -->
          <div v-show="showAdvanced" class="advanced-search">
            <div class="search-row">
              <a-form-item label="手机号">
                <a-input v-model:value="searchForm.phone" placeholder="请输入手机号" />
              </a-form-item>
              <a-form-item label="邮箱">
                <a-input v-model:value="searchForm.email" placeholder="请输入邮箱" />
              </a-form-item>
              <a-form-item label="收货地址">
                <a-input v-model:value="searchForm.addressName" placeholder="请输入收货地址" />
              </a-form-item>
              <!-- 只有管理员可以看到农户相关查询字段 -->
              <template v-if="isAdmin">
                <a-form-item label="农户ID">
                  <a-input v-model:value="searchForm.farmerId" placeholder="请输入农户ID" />
                </a-form-item>
                <a-form-item label="农户名称">
                  <a-input v-model:value="searchForm.farmName" placeholder="请输入农户名称" />
                </a-form-item>
              </template>
            </div>
            <div class="search-row">
              <a-form-item label="订单金额">
                <a-space>
                  <a-input-number v-model:value="searchForm.minTotalPrice" placeholder="最小金额" style="width: 110px" />
                  <span>-</span>
                  <a-input-number v-model:value="searchForm.maxTotalPrice" placeholder="最大金额" style="width: 110px" />
                </a-space>
              </a-form-item>
              <a-form-item label="商品数量">
                <a-space>
                  <a-input-number v-model:value="searchForm.minQuantity" placeholder="最小数量" style="width: 110px" />
                  <span>-</span>
                  <a-input-number v-model:value="searchForm.maxQuantity" placeholder="最大数量" style="width: 110px" />
                </a-space>
              </a-form-item>
            </div>
            <div class="search-row">
              <a-form-item label="创建时间">
                <a-range-picker v-model:value="createTimeRange" @change="handleCreateTimeChange" style="width: 350px" show-time />
              </a-form-item>
              <a-form-item label="支付时间">
                <a-range-picker v-model:value="paymentTimeRange" @change="handlePaymentTimeChange" style="width: 350px" show-time />
              </a-form-item>
            </div>
          </div>
        </a-form>
      </div>

      <!-- 标签页 -->
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange" class="order-tabs">
        <a-tab-pane v-for="(config, key) in ORDER_TAB_CONFIG" :key="key" :tab="config.label" />
      </a-tabs>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="orderList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderStatus'">
            <a-tag :color="getOrderStatusColor(record.orderStatus)">
              {{ ORDER_STATUS_TEXT[record.orderStatus] }}
            </a-tag>
          </template>
          <template v-if="column.key === 'paymentStatus'">
            <a-tag :color="getPaymentStatusColor(record.paymentStatus)">
              {{ PAYMENT_STATUS_TEXT[record.paymentStatus] }}
            </a-tag>
          </template>
          <template v-if="column.key === 'totalPrice'">
            ¥{{ record.totalPrice?.toFixed(2) }}
          </template>
          <template v-if="column.key === 'product'">
            <a-space>
              <span>{{ record.product?.name }}</span>
<!--              <span style="color: #999">{{ record.productSKUVO?.quantity }}</span>-->
<!--              <span style="color: #666">x{{ record.quantity }}</span>-->
            </a-space>
          </template>
          <template v-if="column.key === 'user'">
            <a-space direction="vertical" size="small">
              <span>{{ record.user?.userName }}</span>
              <span style="color: #999">{{ record.user?.phone }}</span>
            </a-space>
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleDetail(record)">详情</a-button>
              <!-- 已支付但未发货的订单显示发货按钮，仅农户可见 -->
              <a-button
                v-if="record.orderStatus === ORDER_STATUS.PAID && isFarmer"
                type="link"
                @click="handleDeliver(record)"
              >
                发货
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 订单详情抽屉 -->
    <a-drawer
      v-model:visible="detailVisible"
      title="订单详情"
      placement="right"
      width="600"
      :footer="false"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="订单编号">{{ currentOrder?.id }}</a-descriptions-item>
        <a-descriptions-item label="订单状态">
          <a-space>
            <a-tag :color="getOrderStatusColor(currentOrder?.orderStatus)">
              {{ ORDER_STATUS_TEXT[currentOrder?.orderStatus] }}
            </a-tag>
            <a-tag :color="getPaymentStatusColor(currentOrder?.paymentStatus)">
              {{ PAYMENT_STATUS_TEXT[currentOrder?.paymentStatus] }}
            </a-tag>
          </a-space>
        </a-descriptions-item>
        <a-descriptions-item label="订单金额">¥{{ currentOrder?.totalPrice?.toFixed(2) }}</a-descriptions-item>
        <a-descriptions-item label="支付时间">{{ formatDateTime(currentOrder?.paymentTime) }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ formatDateTime(currentOrder?.createTime) }}</a-descriptions-item>
        <a-descriptions-item label="农户ID">{{ currentOrder?.farmerId }}</a-descriptions-item>
        <a-descriptions-item label="农户名称">{{ currentOrder?.farmName }}</a-descriptions-item>
      </a-descriptions>

      <a-divider orientation="left">用户信息</a-divider>
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="用户名">{{ currentOrder?.user?.userName }}</a-descriptions-item>
        <a-descriptions-item label="联系电话">{{ currentOrder?.user?.phone }}</a-descriptions-item>
        <a-descriptions-item label="邮箱">{{ currentOrder?.user?.email }}</a-descriptions-item>
      </a-descriptions>

      <a-divider orientation="left">收货信息</a-divider>
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="收货人">{{ currentOrder?.address?.userName }}</a-descriptions-item>
        <a-descriptions-item label="联系电话">{{ currentOrder?.address?.phone }}</a-descriptions-item>
        <a-descriptions-item label="收货地址">{{ currentOrder?.address?.addressName }}</a-descriptions-item>
      </a-descriptions>

      <a-divider orientation="left">商品信息</a-divider>
      <div class="product-info">
        <div class="product-item">
          <img :src="currentOrder?.product?.image" alt="商品图片" class="product-img">
          <div class="product-detail">
            <div class="product-name">{{ currentOrder?.product?.name }}</div>
            <div class="product-spec">规格：{{ currentOrder?.productSKUVO?.quantity }}</div>
            <div class="product-price">
              <span>¥{{ currentOrder?.productSKUVO?.price }}</span>
              <span class="product-quantity">x {{ currentOrder?.quantity }}</span>
            </div>
          </div>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { formatDateTime } from '@/utils/format'
import { listOrderVoByPageUsingPost, getOrderVoByIdUsingGet, deliverOrderUsingPost, listFarmerOrderByPageUsingPost } from '@/api/orderController'
import { message } from 'ant-design-vue'
import {
  ORDER_STATUS_TEXT,
  PAYMENT_STATUS_TEXT,
  ORDER_TAB_CONFIG,
  ORDER_TAB_STATUS,
  ORDER_STATUS
} from '@/constants/order'
import { USER_ROLE } from '@/constants/user'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'
import { DownOutlined } from '@ant-design/icons-vue'

// 获取用户信息和角色
const userStore = useUserStore()
const isAdmin = computed(() => userStore.userInfo?.userRole === USER_ROLE.ADMIN)
const isFarmer = computed(() => userStore.userInfo?.userRole === USER_ROLE.FARMER)

// 当前标签页
const activeTab = ref(ORDER_TAB_STATUS.ALL)

// 表格列定义
const columns = [
  {
    title: '订单编号',
    dataIndex: 'id',
    key: 'id',
    width: 100,
    sorter: true
  },
  {
    title: '用户信息',
    key: 'user',
    width: 150
  },
  {
    title: '商品信息',
    key: 'product',
    width: 250
  },
  {
    title: '订单金额',
    dataIndex: 'totalPrice',
    key: 'totalPrice',
    width: 120,
    sorter: true
  },
  {
    title: '订单状态',
    key: 'orderStatus',
    width: 100
  },
  {
    title: '支付状态',
    key: 'paymentStatus',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
    fixed: 'right'
  }
]

// 表格数据
const orderList = ref<API.OrderVO[]>([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 详情抽屉
const detailVisible = ref(false)
const currentOrder = ref<API.OrderVO | null>(null)

// 搜索表单
const searchForm = ref<Partial<API.OrderAllQueryRequest>>({
  id: undefined,
  userName: undefined,
  phone: undefined,
  email: undefined,
  addressName: undefined,
  productName: undefined,
  minTotalPrice: undefined,
  maxTotalPrice: undefined,
  minQuantity: undefined,
  maxQuantity: undefined,
  createTimeStart: undefined,
  createTimeEnd: undefined,
  paymentTimeStart: undefined,
  paymentTimeEnd: undefined,
  current: 1,
  pageSize: 10
})

// 时间范围
const createTimeRange = ref<any[]>([])
const paymentTimeRange = ref<any[]>([])

// 高级搜索显示状态
const showAdvanced = ref(false)

// 创建时间范围变化
const handleCreateTimeChange = (dates: any[]) => {
  if (dates && dates.length === 2) {
    searchForm.value.createTimeStart = dates[0].format('YYYY-MM-DDTHH:mm:ss')
    searchForm.value.createTimeEnd = dates[1].format('YYYY-MM-DDTHH:mm:ss')
  } else {
    searchForm.value.createTimeStart = undefined
    searchForm.value.createTimeEnd = undefined
  }
}

// 支付时间范围变化
const handlePaymentTimeChange = (dates: any[]) => {
  if (dates && dates.length === 2) {
    searchForm.value.paymentTimeStart = dates[0].format('YYYY-MM-DDTHH:mm:ss')
    searchForm.value.paymentTimeEnd = dates[1].format('YYYY-MM-DDTHH:mm:ss')
  } else {
    searchForm.value.paymentTimeStart = undefined
    searchForm.value.paymentTimeEnd = undefined
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchOrderList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    id: undefined,
    userName: undefined,
    phone: undefined,
    email: undefined,
    addressName: undefined,
    productName: undefined,
    minTotalPrice: undefined,
    maxTotalPrice: undefined,
    minQuantity: undefined,
    maxQuantity: undefined,
    createTimeStart: undefined,
    createTimeEnd: undefined,
    paymentTimeStart: undefined,
    paymentTimeEnd: undefined,
    sortField: undefined,
    sortOrder: undefined,
    farmerId: undefined,
    farmName: undefined,
    current: 1,
    pageSize: 10
  }
  createTimeRange.value = []
  paymentTimeRange.value = []
  handleSearch()
}

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    // 根据用户角色选择不同的API接口
    let res
    const params = {
      ...searchForm.value,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      orderStatus: ORDER_TAB_CONFIG[activeTab.value].orderStatus,
      paymentStatus: ORDER_TAB_CONFIG[activeTab.value].paymentStatus
    }
    
    if (isFarmer.value) {
      // 农户使用专用接口，移除农户相关查询字段
      const { farmerId, farmName, ...farmerParams } = params
      res = await listFarmerOrderByPageUsingPost(farmerParams)
    } else {
      // 管理员使用原有接口，可以使用所有查询字段
      res = await listOrderVoByPageUsingPost(params)
    }
    
    orderList.value = res.data.records
    pagination.value.total = res.data.total
  } finally {
    loading.value = false
  }
}

// 标签页切换
const handleTabChange = () => {
  pagination.value.current = 1
  fetchOrderList()
}

// 表格变化
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  // 处理分页
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize

  // 处理排序
  if (sorter) {
    searchForm.value.sortField = sorter.field
    searchForm.value.sortOrder = sorter.order === 'ascend' ? 'asc' : sorter.order === 'descend' ? 'desc' : undefined
  } else {
    searchForm.value.sortField = undefined
    searchForm.value.sortOrder = undefined
  }

  fetchOrderList()
}

// 订单状态颜色
const getOrderStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    pending: 'warning',
    paid: 'processing',
    shipped: 'blue',
    completed: 'success',
    cancelled: 'default',
    refunded: 'red'
  }
  return colors[status] || 'default'
}

// 支付状态颜色
const getPaymentStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    pending: 'warning',
    success: 'success',
    failed: 'error',
    refunded: 'red'
  }
  return colors[status] || 'default'
}

// 查看详情
const handleDetail = async (record: API.OrderVO) => {
  try {
    const res = await getOrderVoByIdUsingGet({ id: record.id })
    currentOrder.value = res.data
    detailVisible.value = true
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 发货处理
const handleDeliver = async (record: API.OrderVO) => {
  // 只有农户角色才能发货
  if (!isFarmer.value) {
    message.warning('您没有发货权限')
    return
  }
  
  try {
    await deliverOrderUsingPost({
      id: record.id
    })
    message.success('发货成功')
    // 刷新列表
    fetchOrderList()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}
onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped>
.order-container {
  padding: 24px;
  background: #f0f2f5;
}

.search-wrapper {
  margin-bottom: 16px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.search-row:last-child {
  margin-bottom: 0;
}

.search-buttons {
  margin-left: auto;
  margin-right: 0;
}

:deep(.ant-form-item) {
  margin-bottom: 0;
  margin-right: 0;
}

:deep(.ant-form-item-label) {
  min-width: 80px;
}

.advanced-search {
  margin-top: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.order-tabs {
  margin-bottom: 16px;
}

/* 展开/收起按钮图标动画 */
:deep(.anticon) {
  transition: transform 0.3s;
}

.product-info {
  background: #fafafa;
  padding: 16px;
  border-radius: 4px;
}

.product-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: #fff;
  border-radius: 4px;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 12px;
  border-radius: 4px;
}

.product-detail {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 8px;
}

.product-spec {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
}

.product-price {
  color: #ff4d4f;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-quantity {
  color: #666;
  font-size: 13px;
}
</style>
